import express from "express";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
const app = express();
const port = 3000;
app.use(express.json());
//查詢
app.get("/", async (req, res) => {
  const data = await prisma.user.findMany({
    include: {
      posts: true,
    },
  });
  res.send(data);
});
//查詢
app.get("/user/:id", async (req, res) => {
  const data = await prisma.user.findMany({
    where: {
      id: +req.params.id,
    },
    include: {
      posts: true,
    },
  });
  res.send(data);
});
//新增
app.post("/create", async (req, res) => {
  const { name, email } = req.body;
  const data = await prisma.user.create({
    data: {
      name,
      email,
      posts: {
        create: [
          {
            title: "文章1",
            content: "文章的內容",
          },
          {
            title: "文章2",
            content: "文章2的內容",
          },
        ],
      },
    },
  });
  res.send(data);
});
//编辑
app.post("/update", async (req, res) => {
  const { name, email, id } = req.body;
  const data = await prisma.user.update({
    where: {
      id,
    },
    data: {
      name,
      email,
    },
  });
  res.send(data);
});
//删除
app.post("/delete", async (req, res) => {
  //因为绑定了外键，所以要先级联刪除post
  await prisma.post.deleteMany({
    where: {
      userId: +req.body.id,
    },
  });
  const { id } = req.body;
  const data = await prisma.user.delete({
    where: {
      id,
    },
  });
  res.send(data);
});
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
